package com.gongpingjialoan.activity.car;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.adapter.BrowseAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.AssessHistory;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.widget.LoadingDialog;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/5/12.
 */
public class BrowseActivity extends BaseActivity implements NetDataJson.OnNetDataJsonListener, AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener<ListView>, PullToRefreshBase.OnLastItemVisibleListener {

    private PullToRefreshListView pullToRefreshListView;

    private ImageView nodataImageView;

    private ListView listView;

    private View footView;

    private List<AssessHistory> mAssessHistories;

    private NetDataJson mNetDataJson, deleteNetDataJson;

    private BrowseAdapter mBrowseAdapter;

    public int mPage;

    public boolean mIsLoadingMore = true;

    public boolean mHasMore;

    public boolean isRefresh;

    private TextView editTextView;

    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSendData = true;
        isScrollPage = true;
        action = "my_viewRecord";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.browse_layout);
        setTitle("浏览记录");
        loadingDialog = new LoadingDialog(this);
        editTextView = (TextView) findViewById(R.id.right_title);

        editTextView.setText("清空");
        footView = LayoutInflater.from(this).inflate(R.layout.listview_footview, null);
        nodataImageView = (ImageView) findViewById(R.id.no_info);
        pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.listview);
        pullToRefreshListView.setScrollingWhileRefreshingEnabled(false);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        pullToRefreshListView.setOnRefreshListener(this);
        pullToRefreshListView.setOnLastItemVisibleListener(this);
        editTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder ab = new AlertDialog.Builder(BrowseActivity.this);
                ab.setTitle("清空");
                ab.setMessage("确定要清空所有记录吗?");
                ab.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                ab.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (deleteNetDataJson == null) {
                            deleteNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                                @Override
                                public void onDataJsonError(String errorMessage) {
                                    loadingDialog.dismiss();
                                    Toast.makeText(BrowseActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onDataJsonUpdate(JSONObject json) {
                                    loadingDialog.dismiss();
                                    Toast.makeText(BrowseActivity.this, "删除成功!", Toast.LENGTH_SHORT).show();
                                    pullToRefreshListView.setRefreshing();
                                    if (MainActivity.main.assessmentFragment != null && MainActivity.main.assessmentFragment.isAdded()) {
                                        MainActivity.main.assessmentFragment.mMainRecomendView.getBrowseCars();
                                    }
                                }
                            });
                        }
                        deleteNetDataJson.addParam("record_type", "buy_car");
                        deleteNetDataJson.addParam("ids", "all");
                        deleteNetDataJson.setUrl(API.deleteCollectCar);
                        deleteNetDataJson.request("post");
                        loadingDialog.show();
                    }
                });
                ab.create().show();

            }
        });
        mAssessHistories = new ArrayList<>();
        mBrowseAdapter = new BrowseAdapter(mAssessHistories, this);
        listView = pullToRefreshListView.getRefreshableView();
        listView.addFooterView(footView);
        listView.setAdapter(mBrowseAdapter);
        listView.setOnItemClickListener(this);
        listView.removeFooterView(footView);

        mNetDataJson = new NetDataJson(this);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                pullToRefreshListView.setRefreshing();
            }
        }, 300);
    }

    private void refresh() {
        mPage = 1;
        mHasMore = true;
        isRefresh = true;
        editTextView.setVisibility(View.GONE);
        nodataImageView.setVisibility(View.GONE);
        updateData();

    }


    private void updateData() {
        mNetDataJson.cancelTask();
        mNetDataJson.addParam("page", mPage);
        mNetDataJson.addParam("record_type", "buy_car");
        mNetDataJson.setUrl(API.collectHistory);
        mNetDataJson.request("get");
    }


    @Override
    public void onLastItemVisible() {
        if (!mHasMore) {
            // Toast.makeText(this, "没有更多了", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!mIsLoadingMore && mHasMore) {
            listView.addFooterView(footView);
            listView.setSelection(listView.getBottom());
            isRefresh = false;
            mIsLoadingMore = true;
            mPage++;
            updateData();
        }
    }

    boolean isFristLoading = true;

    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        if (!isFristLoading) {
            String label =
                    "更新时间:" + DateUtils.formatDateTime(this, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                            | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
            refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
        }
        isFristLoading = false;
        refresh();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0) return;
        AssessHistory carSource = (AssessHistory) view.getTag(R.id.tag_second);
        Intent intent = new Intent();
        if ("promo_car".equals(carSource.record_type)) {
            intent.setClass(this, DiscountDetailActivity.class);
            intent.putExtra("typevalue", String.valueOf(carSource.promo_car_id));
            startActivity(intent);
        } else {
            intent.setClass(this, CarBuyDetailActivity.class);
            intent.putExtra("typevalue", String.valueOf(carSource.car_id));
            intent.putExtra("type", "fromHistory");
            intent.putExtra("from", "favorite");
            startActivity(intent);
        }
    }

    @Override
    public void onDataJsonError(String errorMessage) {
        if (!isRefresh && mIsLoadingMore) {
            listView.removeFooterView(footView);
        }
        mIsLoadingMore = false;
        Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
        pullToRefreshListView.onRefreshComplete();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mNetDataJson != null) {
            mNetDataJson.cancelTask();
            mNetDataJson = null;
        }

    }

    @Override
    public void onDataJsonUpdate(JSONObject json) {
        if (!isRefresh && mIsLoadingMore) {
            listView.removeFooterView(footView);
        }
        JSONArray jsonArray = null;
        if (isRefresh) {
            mAssessHistories.clear();
            mBrowseAdapter.setData(mAssessHistories);
        }
        try {
            jsonArray = json.getJSONArray("records");
            if (0 == jsonArray.length()) {
                mIsLoadingMore = false;
                nodataImageView.setVisibility(View.VISIBLE);
                pullToRefreshListView.onRefreshComplete();
                editTextView.setVisibility(View.GONE);
                return;
            }

            for (int i = 0; i < jsonArray.length(); i++) {
                AssessHistory ah = new AssessHistory();
                JSONObject object = jsonArray.getJSONObject(i);
                ah.city = object.getString("city");
                ah.model_detail = object.getString("title");
                ah.model_slug = object.getString("model_slug");
                ah.brand = object.getString("brand");
                ah.model_detail_slug = object.getString("model_detail_slug");
                ah.mile = object.getString("mile");
                ah.create_time = object.getString("create_time");
                ah.eval_price = object.getString("eval_price");
                ah.year = object.getString("year");
                ah.brand_slug = object.getString("brand_slug");
                ah.model = object.getString("model");
                ah.url = object.getString("thumbnail");
                ah.record_id = object.getString("record_id");
                ah.car_id = object.getString("car_id");
                ah.review = object.getString("review");
                ah.record_type = object.getString("record_type");
                ah.review_type = object.getString("review_type");
                ah.price = object.getString("price");
                mAssessHistories.add(ah);
            }
            int page_num = json.getInt("total_page");
            if (page_num == mPage) {
                mHasMore = false;
            }
        } catch (JSONException e) {
            mIsLoadingMore = false;
            nodataImageView.setVisibility(View.VISIBLE);
            Toast.makeText(this, "数据异常，请稍后再试", Toast.LENGTH_SHORT).show();
            pullToRefreshListView.onRefreshComplete();
            editTextView.setVisibility(View.GONE);
            return;
        }
        mBrowseAdapter.setData(mAssessHistories);
        pullToRefreshListView.onRefreshComplete();
        editTextView.setVisibility(View.VISIBLE);
        mIsLoadingMore = false;
    }
}
